<template>
	<div class="picture-search-form">
		<!-- 搜索表单 -->
		<a-form layout="inline" :model="searchParams" @finish="doSearch">
			<a-row :gutter="[16, 8]" style="width: 100%">
				<a-col :xs="24" :sm="12" :md="8" :lg="6">
					<a-form-item label="关键词">
						<a-input v-model:value="searchParams.searchText" placeholder="从名称和简介搜索" allow-clear />
					</a-form-item>
				</a-col>
				<a-col :xs="24" :sm="12" :md="8" :lg="6">
					<a-form-item label="类型">
						<a-select
							v-model:value="searchParams.category"
							placeholder="选择图片类型"
							allow-clear
							show-search
							:filter-option="filterCategoryOption"
						>
							<a-select-option v-for="category in categoryOptions" :key="category.value" :value="category.value">
								{{ category.label }}
							</a-select-option>
						</a-select>
					</a-form-item>
				</a-col>
				<a-col :xs="24" :sm="12" :md="8" :lg="6">
					<a-form-item label="标签">
						<a-select
							v-model:value="searchParams.tags"
							mode="multiple"
							placeholder="选择标签"
							allow-clear
							show-search
							:filter-option="filterTagOption"
						>
							<a-select-option v-for="tag in tagOptions" :key="tag.value" :value="tag.value">
								{{ tag.label }}
							</a-select-option>
						</a-select>
					</a-form-item>
				</a-col>
				<a-col :xs="24" :sm="12" :md="8" :lg="6">
					<a-form-item label="格式">
						<a-select v-model:value="searchParams.picFormat" placeholder="选择图片格式" allow-clear show-search>
							<a-select-option v-for="format in formatOptions" :key="format" :value="format">
								{{ format.toUpperCase() }}
							</a-select-option>
						</a-select>
					</a-form-item>
				</a-col>
				<a-form-item label="时间范围">
					<a-range-picker
						v-model:value="timeRange"
						:placeholder="['开始时间', '结束时间']"
						:presets="timePresets"
						@change="handleTimeRangeChange"
						style="width: 100%"
					/>
				</a-form-item>
				<a-form-item label="审核状态" v-if="showReviewStatus">
					<a-select
						v-model:value="searchParams.reviewStatus"
						placeholder="选择审核状态"
						:options="PIC_REVIEW_STATUS_OPTIONS"
						allow-clear
					/>
				</a-form-item>
				<a-form-item>
					<a-space>
						<a-button type="primary" html-type="submit">搜索</a-button>
						<a-button type="default" @click="resetSearch">重置</a-button>
					</a-space>
				</a-form-item>
			</a-row>
		</a-form>
	</div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { PIC_REVIEW_STATUS_OPTIONS } from '@/constants/picture'
import { listPictureTagCategoryUsingGet } from '@/api/pictureController'
import { message } from 'ant-design-vue'
import dayjs, { Dayjs } from 'dayjs'

// 定义扩展的搜索参数类型，允许spaceId为string，并添加时间范围字段
type ExtendedPictureQueryRequest = Omit<API.PictureQueryRequest, 'spaceId'> & {
	spaceId?: string | number
	startEditTime?: string
	endEditTime?: string
}

// 定义Props
interface Props {
	// 初始搜索参数（支持string类型的spaceId）
	initSearchParams?: Partial<ExtendedPictureQueryRequest>
	// 是否显示审核状态字段（管理员页面显示，个人空间不显示）
	showReviewStatus?: boolean
}

// 定义Emits
interface Emits {
	(e: 'search', searchParams: ExtendedPictureQueryRequest): void
	(e: 'reset', searchParams: ExtendedPictureQueryRequest): void
}

const props = withDefaults(defineProps<Props>(), {
	showReviewStatus: false,
	initSearchParams: () => ({}),
})

const emit = defineEmits<Emits>()

// 分类和标签选项
const categoryOptions = ref<{ value: string; label: string }[]>([])
const tagOptions = ref<{ value: string; label: string }[]>([])

// 格式选项（基于常见的图片格式）
const formatOptions = ref<string[]>(['jpg', 'jpeg', 'png', 'webp'])

// 时间范围相关状态
const timeRange = ref<[Dayjs, Dayjs] | null>(null)

// 时间预设配置
const timePresets = [
	{
		label: '过去7天',
		value: [dayjs().subtract(7, 'day').startOf('day'), dayjs().endOf('day')],
	},
	{
		label: '过去14天',
		value: [dayjs().subtract(14, 'day').startOf('day'), dayjs().endOf('day')],
	},
	{
		label: '过去30天',
		value: [dayjs().subtract(30, 'day').startOf('day'), dayjs().endOf('day')],
	},
	{
		label: '过去90天',
		value: [dayjs().subtract(90, 'day').startOf('day'), dayjs().endOf('day')],
	},
]

// 搜索条件
const searchParams = reactive<ExtendedPictureQueryRequest>({
	current: 1,
	pageSize: 10,
	sortField: 'createTime',
	sortOrder: 'descend',
	searchText: '',
	category: '',
	tags: [],
	picFormat: '',
	reviewStatus: undefined,
	startEditTime: undefined,
	endEditTime: undefined,
	...props.initSearchParams,
})

// 搜索操作
const doSearch = () => {
	// 重置当前页为1
	searchParams.current = 1
	// 触发搜索事件
	emit('search', { ...searchParams })
}

// 重置搜索条件
const resetSearch = () => {
	// 重置搜索参数
	Object.assign(searchParams, {
		current: 1,
		pageSize: 10,
		sortField: 'createTime',
		sortOrder: 'descend',
		searchText: '',
		category: '',
		tags: [],
		picFormat: '',
		reviewStatus: undefined,
		startEditTime: undefined,
		endEditTime: undefined,
		...props.initSearchParams,
	})

	// 重置时间相关状态
	timeRange.value = null

	// 触发重置事件
	emit('reset', { ...searchParams })
}

// 分类选项过滤
const filterCategoryOption = (input: string, option: any) => {
	return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
}

// 标签选项过滤
const filterTagOption = (input: string, option: any) => {
	return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
}

// 处理时间范围变化
const handleTimeRangeChange = (dates: [Dayjs, Dayjs] | null) => {
	if (!dates || dates.length !== 2) {
		searchParams.startEditTime = undefined
		searchParams.endEditTime = undefined
		return
	}

	const [startDate, endDate] = dates
	searchParams.startEditTime = startDate.startOf('day').toISOString()
	searchParams.endEditTime = endDate.endOf('day').toISOString()
}

// 获取分类和标签选项
const getTagCategoryOptions = async () => {
	try {
		const res = await listPictureTagCategoryUsingGet()
		if (res.data.code === 0 && res.data.data) {
			// 设置分类选项
			categoryOptions.value = (res.data.data.categoryList ?? []).map((data: string) => ({
				value: data,
				label: data,
			}))

			// 设置标签选项
			tagOptions.value = (res.data.data.tagList ?? []).map((data: string) => ({
				value: data,
				label: data,
			}))
		} else {
			message.error('获取分类标签失败: ' + res.data.message)
		}
	} catch {
		message.error('获取分类标签失败，请重试')
	}
}

// 暴露方法供父组件调用
defineExpose({
	searchParams,
	doSearch,
	resetSearch,
})

// 页面加载时获取分类和标签选项
onMounted(() => {
	getTagCategoryOptions()
})


</script>

<style lang="scss" scoped>
.picture-search-form {
	background: #fafafa;
	border-radius: 8px;

	:deep(.ant-form-item) {
		margin-bottom: 8px;
	}

	:deep(.ant-form-item-label) {
		font-weight: 500;
		color: #666;
	}

	:deep(.ant-select),
	:deep(.ant-input),
	:deep(.ant-picker) {
		width: 100%;
	}

	:deep(.ant-btn) {
		min-width: 80px;
	}
}

// 响应式设计
@media (max-width: 768px) {
	.picture-search-form {
		padding: 12px;

		:deep(.ant-col) {
			margin-bottom: 8px;
		}
	}
}
</style>

<style scoped lang="scss">
.picture-search-form {
	// 表单项间距优化
	.ant-form {
		gap: 8px;
	}

	// 时间范围组件样式
	.ant-space-vertical {
		.ant-select,
		.ant-picker {
			width: 100%;
		}
	}

	// 响应式布局优化
	@media (max-width: 768px) {
		.ant-form-item {
			margin-bottom: 12px;
		}
	}
}
</style>
